﻿using UnityEngine;
using UnityEditor;
using NUnit.Framework;

//自定义Tset脚本
[CustomEditor(typeof(AssetData))]
//在编辑模式下执行脚本，这里用处不大可以删除。
[ExecuteInEditMode]
public class CreateAssetDataFilter : Editor
{
    //在这里方法中就可以绘制面板。
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        //得到Test对象
        AssetData test = (AssetData)target;

        if (GUILayout.Button("Create Assets"))
        {
            Debug.Log(test.asset);
            Debug.Log(test.path);
            for (int i = 0; i < test.asset.Count; i++)
            {
                AssetDatabase.CreateAsset(test.asset[i], "Assets/" + test.path[i] + ".asset");
            }


            //新建一个简单的材质资源
            //var material = new Material (Shader.Find("Specular"));
            //AssetDatabase.CreateAsset(material, "Assets/MyMaterial.mat");

            // Print the path of the created asset
            //打印新建资源的路径
            //Debug.Log(AssetDatabase.GetAssetPath(material));
        }

        if (GUILayout.Button("Create All Prefab Assets"))
        {
            for (int i = 0; i < test.names.Count; i++)
            {
                CreatePrefab(test.obj[i], test.mesh[i], test.uv1[i], test.uv2[i], test.material[i], test.names[i]);
            }
        }

    }

    private static void CreatePrefab(GameObject obj, Mesh mesh, Texture2D uv1, Texture2D uv2, Material material, string name)
    {
        var _assetPrefab = PrefabUtility.CreateEmptyPrefab("Assets/A/"+ name + ".prefab");
        var gameobj = PrefabUtility.ReplacePrefab(obj, _assetPrefab, ReplacePrefabOptions.ReplaceNameBased);
        gameobj.name = name;
        mesh.name = "mesh";
        AssetDatabase.AddObjectToAsset(mesh, _assetPrefab);
        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(mesh));

        uv1.name = "uv1";
        AssetDatabase.AddObjectToAsset(uv1, _assetPrefab);
        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(uv1));

        uv2.name = "uv2";
        AssetDatabase.AddObjectToAsset(uv2, _assetPrefab);
        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(uv2));

        material.name = "material";
        AssetDatabase.AddObjectToAsset(material, _assetPrefab);
        AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(material));

        material.SetTexture("_MainTex", uv1);
        material.SetTexture("_ShadowTex", uv2);
        gameobj.GetComponent<MeshFilter>().mesh = mesh;
        gameobj.GetComponent<MeshRenderer>().material = material;

        AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
        AssetDatabase.SaveAssets();
    }
}
